<!DOCTYPE html>
<html lang="en" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro"
      xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <link rel="stylesheet" href="/layui/css/layui.css">
  <link rel="stylesheet" href="/css/custom.form.css">
  <style>
    .custom-tree-item-clicked{color:#FC9003}
  </style>
</head>
<body>
<div class="panel panel-default" id="addDiv" hidden>
<div class="layui-card-body" >
<form class="layui-form " action="" lay-filter="info" style="width: 400px;margin-top: 10px">
  <input name="id" id="id" hidden/>
  <div class="layui-form-item">
    <label class="layui-form-label">学期</label>
    <div class="layui-input-inline">
      <select id="termId" name="termId" lay-filter="select-term" th:with="beans=${@dlTermService.getJSONList()}" lay-search="" lay-verify="required" >
        <option value="">请选择</option>
        <option th:each="bean : ${beans}" th:text="${bean.title}" th:value="${bean.id}"></option>
      </select>
    </div>
  </div>
  <div class="layui-form-item">
    <label class="layui-form-label">教师</label>
    <div class="layui-input-inline">
      <select id="teacherId" name="teacherId" lay-filter="select-teacher" th:with="teachers=${@userServiceImpl.getTeachers()}" lay-search="" lay-verify="required">
        <option value="">请选择</option>
        <option th:each="teacher : ${teachers}" th:text="${teacher.realName}" th:value="${teacher.id}"></option>
      </select>
    </div>
  </div>
  <div class="layui-form-item">
    <label class="layui-form-label">课程</label>
    <div class="layui-input-inline">
      <select id="courseId" name="courseId" lay-filter="select-course" lay-search="" lay-verify="required">
        <option value="">请选择</option>
      </select>
    </div>
  </div>
  <div class="layui-form-item">
    <label class="layui-form-label">班级</label>
    <div class="layui-input-inline">
      <select id="classId" name="classId" lay-filter="select-teacher" th:with="clazzs=${@dlClassService.getClassList()}" lay-search="">
        <option value="">请选择</option>
        <option th:each="clazz : ${clazzs}" th:text="${clazz.grade.gradeNameLabel + ' ' + clazz.classNo + '班'}" th:value="${clazz.id}"></option>
      </select>
    </div>
  </div>
  <div class="layui-form-item">
  <div class="layui-input-block">
    <button type="submit" class="layui-btn" lay-submit="" lay-filter="submit">保存</button>
    <button  class="layui-btn layui-btn-primary" id="btn_cancel">返回</button>
  </div>
</div>
</form>
</div>
</div>
<div class="layui-fluid">
  <div class="layui-row layui-col-space15">
    <div class="layui-col-sm12 layui-col-md2 layui-col-lg2">
      <div class="layui-card">

        <div class="layui-card-body mini-bar" id="leftTree">

        </div>
      </div>
    </div>
    <div class="layui-col-sm12 layui-col-md10 layui-col-lg10">
      <div class="table_div">
        <div id="searchParam"  shiro:hasPermission="dlClassTeacher:list">
          <div class="layui-form-item layui-form">

            <label class="layui-form-label">学期</label>
            <div class="layui-input-inline">
              <select id="s_termId" name="classId" lay-filter="select-term" th:with="beans=${@dlTermService.getAllJSONList()}" lay-search="">
                <option value="">请选择</option>
                <option th:each="bean : ${beans}" th:text="${bean.title}" th:value="${bean.id}"></option>
              </select>
            </div>
            <label class="layui-form-label">教师</label>
            <div class="layui-input-inline">
              <select id="s_teacherId" name="s_teacherId" lay-filter="select-teacher" th:with="teachers=${@userServiceImpl.getTeachers()}" lay-search="" lay-verify="required">
                <option value="">请选择</option>
                <option th:each="teacher : ${teachers}" th:text="${teacher.realName}" th:value="${teacher.id}"></option>
              </select>
            </div>
            <div class="layui-input-inline ">
              <button class="layui-btn" onclick="search()"  id="search">查询</button>
            </div>
          </div>

        </div>
        <table class="layui-table" id="showTable" lay-filter="showTable" ></table>
      </div>
    </div>
  </div>
</div>
<script type="text/html" id="toolbar">
  <div class="layui-btn-container">
    <button class="layui-btn layui-btn-sm" lay-event="add"  shiro:hasPermission="dlClassTeacher:add">添加任课老师</button>
    <button class="layui-btn layui-btn-sm" lay-event="batchDeleted" shiro:hasPermission="dlClassTeacher:delete">删除</button>
  </div>
</script>
<script type="text/html" id="tool">
  <a class="layui-btn layui-btn-xs" lay-event="edit" shiro:hasPermission="dlClassTeacher:update">编辑</a>
  <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del" shiro:hasPermission="dlClassTeacher:delete">删除</a>
</script>

</body>
</html>
<script src="/layui/layui.all.js"></script>
<script src="/js/core.util.js"></script>
<script>
  //获取token
  var token = CoreUtil.getData("access_token");

  var teacherData = "[[${@userServiceImpl.getTeachers()}]]".replace(/&quot;/g,"\"");
  var classData = "[[${@dlClassService.getClassList()}]]".replace(/&quot;/g,"\"");
  var courseData = "[[${@dlCourseService.getJSONList()}]]".replace(/&quot;/g,"\"");

  var termDatas = "[[${@dlTermService.getAllJSONList()}]]".replace(/&quot;/g,"\"");

  //自定义变量
  var classId = null;//班级ID


  //地址栏转义token中的#号
  var tokenQuery = token.replace("#", "%23");
  var tableIns1;
  var table = layui.table;
  var form = layui.form;
  var tree = layui.tree;
  var layer = layui.layer;
  var $ = jQuery = layui.jquery;
  var laydate = layui.laydate;

  layui.use(['table', 'layer', 'laydate'], function () {
    loadLeftTree();
    //加载table
    tableIns1 = table.render({
      elem: '#showTable'
      , contentType: 'application/json'
      , headers: {"authorization": token}
      , page: true //开启分页
      , url: '/dlClassTeacher/listByPage' //数据接口
      , method: 'POST'
      , parseData: function (res) { //将原始数据解析成 table 组件所规定的数据
        return {
          "code": res.code, //解析接口状态
          "msg": res.msg, //解析提示文本
          "count": CoreUtil.isEmpty(res.data) ? 0 : res.data.total, //解析数据长度
          "data": CoreUtil.isEmpty(res.data) ? null : res.data.records //解析数据列表
        }
      }
      , cols: [
        [
          {type: 'checkbox', fixed: 'left'},
          {field: 'id', title: '', sort: true, hide: true},
          {field: 'termId', title: '学期', width: 230, sort: true, templet: function(item){
              return CoreUtil.getBeanLabel(termDatas, item.termId, 'id', 'title');
            }
          },
          {field: 'teacherId', title: '教师', sort: true, templet: function(item){
               return CoreUtil.getBeanLabel(teacherData, item.teacherId, "id", "realName", "phone")
            }
          },
          {field: 'courseId', title: '课程', sort: true, templet: function(item){
                return CoreUtil.getBeanLabel(courseData, item.courseId, "id", "name");
            }
          },
          {field: 'classId', title: '班级', sort: true, templet: function(item){
              return CoreUtil.getClassLabel(classData, item.classId);
            }
          },
          {width: 120, toolbar: "#tool", title: '操作'}
        ]
      ]
      , toolbar: '#toolbar'
    });


    //表头工具
    table.on('toolbar(showTable)', function(obj){
      switch(obj.event){
        case 'batchDeleted':
          var checkStatus = table.checkStatus(obj.config.id);
          var data = checkStatus.data;
          if(data.length==0){
            layer.msg("请选择要批量删除的列");
          }else {
            var ids = [];
            $(data).each(function (index,item) {
              ids.push(item.id);
            });
            tipDialog(ids);
          }
          break;
        case 'add':
          if(classId == null){
            layer.msg("请选择班级");
            break;
          }
          loadCourseSelect(classId);
          // $(".table_div").hide();
          // $("#leftTree").hide();
          // $(".operation").show();

          layer.open({
            type: 1,
            title: "新增",
            area: ['430px', '500px'],
            content: $('#addDiv')
          });

          // $(".title").html("新增");
          $(".operation input[name=id]").val("");
          $("#teacherId").val("");
          $("#courseId").val("");
          $("#id").val("");
          if(!CoreUtil.isEmpty(classId)){
            $("#classId").find('option[value="'+classId+'"]').prop('selected',true);
            $("#classId").prop("disabled", true);
          }

          $("#termId").val("");

          form.render("select");

          break;
      };
    });
    //列操作
    table.on('tool(showTable)',function (obj) {
      var data = obj.data;
      switch (obj.event) {
        case 'del':
          var ids=[];
          ids.push(data.id);
          tipDialog(ids);
          break;
        case 'edit':
          // $(".table_div").hide();
          // $("#leftTree").hide();
          // $(".operation").show();

          layer.open({
            type: 1,
            title: "编辑",
            area: ['430px', '500px'],
            content: $('#addDiv')
          });


          loadCourseSelect(data.classId);
          // $(".title").html("编辑");
          $("#id").val(data.id);
          $(".operation input[name=teacherId]").val(data.teacherId);
          if(!CoreUtil.isEmpty(data.teacherId)){
            $("#teacherId").find('option[value="'+data.teacherId+'"]').prop('selected',true);
          }
          if(!CoreUtil.isEmpty(data.courseId)){
            $("#courseId").find('option[value="'+data.courseId+'"]').prop('selected',true);
          }
          if(!CoreUtil.isEmpty(data.classId)){
            $("#classId").find('option[value="'+data.classId+'"]').prop('selected',true);
          }
          if(!CoreUtil.isEmpty(data.termId)){
            $("#termId").find('option[value="'+data.termId+'"]').prop('selected',true);
          }
          form.render("select");
          break;
      }
    });

    //导出
    $('#export').on('click', function () {
      //原先分页limit
      var exportParams = {
        limit: 10000,
        key: $("#key").val()
      };
      CoreUtil.sendPost("/dlClassTeacher/listByPage", exportParams, function (res) {
        //初始化渲染数据
        if (res.data != null && res.data.records != null) {
          table.exportFile(tableIns1.config.id, res.data.records, 'xls');
        }
      });
    });

    //删除
    var tipDialog=function (ids) {
      layer.open({
        content: "确定要删除么?",
        yes: function(index, layero){
          layer.close(index); //如果设定了yes回调，需进行手工关闭
          CoreUtil.sendDelete("/dlClassTeacher/delete",ids,function (res) {
            layer.msg(res.msg, {time:1000},function () {
              search();
            });
          });
        }
      });
    };

    //返回
    $("#btn_cancel").click(function() {
      // $(".table_div").show();
      // $("#leftTree").show();
      // $(".operation").hide();
      layer.closeAll();
      return false;
    });

    //监听保存
    form.on('submit(submit)', function(data){
      if(data.field.id===undefined || data.field.id===null || data.field.id===""){
        CoreUtil.sendPost("/dlClassTeacher/add",data.field,function (res) {
          layer.closeAll();
          search();
        });
      }else {
        CoreUtil.sendPut("/dlClassTeacher/update",data.field,function (res) {
          layer.closeAll();
          search();
        });
      }

      return false;
    });
  });


  function loadLeftTree() {
    CoreUtil.sendPost("/dlGrade/getClassTree", null, function (res) {
      var data = res.data;
      console.log(JSON.stringify(data));
      tree.render({
        elem: '#leftTree'
        , data: data
        , onlyIconControl: true  //是否仅允许节点左侧图标控制展开收缩
        , click: function (obj) {
          if(obj.data.id != null && obj.data.id != undefined){
            $('div [data-id="'+classId+'"] div').eq(1).last().css('background-color','');     //清除旧的样式
            classId = obj.data.id;
            $('div [data-id="'+obj.data.id+'"] div').eq(1).last().css('background-color','#87eaa3');
            search();
          }
        }
      });
    })
  };

  function loadCourseSelect(classId){
    var params = {
      classId: classId
    }
    console.log("params:" + JSON.stringify(params));
    CoreUtil.sendPost("/dlCourse/getCourseListByClassId", params, function (res) {
      if(res.code != 0){
        layer.msg(res.msg);
        return;
      }
      var data = res.data;
      var courseId = $("#courseId");
      courseId.empty();
      courseId.append("<option value=\"\">请选择</option>");
      for(var i = 0; i < data.length; i ++){
        courseId.append("<option value='" + data[i].id + "'>" + data[i].name + "</option>");
      }
      form.render();
    }, false);
  }





  //执行查询
  function search() {
    //这里以搜索为例
    tableIns1.reload({
      where: { //设定异步数据接口的额外参数，任意设
        classId: classId,
        termId: $("#s_termId").val(),
        teacherId: $("#s_teacherId").val()
      }
      , page: {
        curr: 1 //重新从第 1 页开始
      }
    });
  };
</script>